package com.superb.soslon.config;

import com.superb.core.domain.entity.EasyModel;
import com.superb.core.service.EasyDeploymentService;
import com.superb.core.service.EasyModelService;
import lombok.SneakyThrows;
import org.flowable.engine.RepositoryService;
import org.noear.solon.Solon;
import org.noear.solon.Utils;
import org.noear.solon.annotation.*;
import org.noear.solon.core.util.IoUtil;
import org.noear.solon.core.util.ResourceUtil;

import java.io.InputStream;

/**
 * @author MoJie
 * @since
 */
@Component
public class InitConfig {

    @Inject
    private EasyModelService modelService;
    @Inject
    private EasyDeploymentService deploymentService;

    /**
     * 初始化一个默认的流程
     * @author MoJie
     */
    @Init
    @SneakyThrows
    @Condition(onBean = RepositoryService.class)
    public void initModel() {
        EasyModel easyModel = modelService.getByKey("bxsp");
        String url = "http://127.0.0.1:" + Solon.cfg().serverPort() + "/easy-flowable/index.html";
        if (easyModel == null) {
            EasyModel model = new EasyModel().setKey("bxsp")
                    .setName("报销审批").setModelType("06")
                    .setRemarks("财务报销走的流程");
            String modelId = modelService.insert(model);
            // 获取提前准备的报销审批xml
            InputStream xml = ResourceUtil.getResourceAsStream("xml/easy-flowable-bxsp.xml");
            String xmlStr = IoUtil.transferToString(xml, "UTF-8");
            // 如果使用ui控制台，会默认返回一个picture，为设计器给的图片
            modelService.updateById(new EasyModel().setId(modelId)
                    .setModelEditorXml(xmlStr));
            // 创建好模型后并部署它
            deploymentService.deploymentModel(modelId);
            System.out.println("\tEasy-Flowable已为您准备好了一个报销审批流程并部署好了\n\t访问:" + url);
        } else {
            System.out.println("\tEasy-Flowable访问地址:" + url +"\n");
        }
    }

}
